/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.googlecode.jsimplemarket.wicket.pages;

import com.googlecode.jsimplemarket.model.Creanta;
import com.googlecode.jsimplemarket.model.Firma;
import com.googlecode.jsimplemarket.model.FisierAtasat;
import com.googlecode.jsimplemarket.model.FisierAtasatFirma;
import com.googlecode.jsimplemarket.model.Inchiriere;
import com.googlecode.jsimplemarket.model.Plata;
import com.googlecode.jsimplemarket.model.RaportIncasari;
import com.googlecode.jsimplemarket.model.TotalIncasari;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.wicket.MarketApp;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Folder;
import org.apache.wicket.util.lang.Bytes;

/**
 *
 * @author Alexandru.Codescu
 */
public class FirmaEditPage extends DefaultEditPage {

    @SpringBean(name = "genericService")
    private GenericService<Firma> service;

    @SpringBean(name = "genericService")
    private GenericService<FisierAtasat> serviceFisierAtasat;
    
    @SpringBean(name = "genericService")
    private GenericService<FisierAtasatFirma> serviceFisierAtasatFirma;
    
    private final Firma entity;


    
    public FirmaEditPage() {
        entity = new Firma();
        init();
    }

    public FirmaEditPage(Long id) {
        entity = service.getById(Firma.class, id);
        init();
    }

    private Form<Firma> createFormFirma() {
        Form<Firma> form = new Form<Firma>("form");
        form.setModel(new CompoundPropertyModel<Firma>(entity));

        TextField<String> tfDenumire = new TextField<String>("denumire");
        tfDenumire.setRequired(true);
        form.add(tfDenumire);

        TextField<String> tfCif = new TextField<String>("cif");
        form.add(tfCif);

        TextArea<String> taAdresa = new TextArea<String>("sediuSocial");
        form.add(taAdresa);

        TextField<String> tfDateContact = new TextField<String>("dateContact");
        form.add(tfDateContact);

        form.add(new SubmitLink("submit") {

            @Override
            public void onSubmit() {
                if (entity.getId() == null) {
                    service.insert(entity);
                } else {
                    service.update(entity);
                }
                setResponsePage(new FirmaViewPage());
            }

        });

        form.add(new Link("renuntare") {

            @Override
            public void onClick() {
                setResponsePage(new FirmaViewPage());
            }

        });

        return form;
    }

    private FileUploadForm createFormUpload() {
        return new FileUploadForm("formUpload");
    }

    private void init() {
    	add(createFormFirma());

    	    	
        add(createFormUpload().setVisible(!entity.isNew()));
        
    }

    class AtasamenteListView extends ListView<FisierAtasatFirma> {

        public AtasamenteListView(String id, List<FisierAtasatFirma> liste) {
            super(id, liste);
        }

        @Override
        protected void populateItem(ListItem<FisierAtasatFirma> li) {
        	int index = li.getIndex() + 1;
            final FisierAtasatFirma fisierAtasatFirma = li.getModelObject();
            li.add(new Label("index", index));
            li.add(new Label("denumireFisier", fisierAtasatFirma.getFisierAtasat().getNumeFisier()));
            li.add(new Label("descriere", fisierAtasatFirma.getFisierAtasat().getDescriere()));

            Folder uploadFolder = MarketApp.get().getUploadFolder();
            Folder fileUploadFolder = new Folder(uploadFolder, "firme" + (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0 ? "\\" : "/") + fisierAtasatFirma.getFirma().getId());
            
            File file = new File(fileUploadFolder, fisierAtasatFirma.getFisierAtasat().getNumeFisier());
            DownloadLink downloadlink = new DownloadLink("lkDescarcare", file, file.getName());
            
            final String path = fileUploadFolder.getAbsolutePath();
            //li.add(new Label("dirpath", path));
            li.add(downloadlink);
            
            Link delLink = new Link("delLink") {
                @Override
                public void onClick() {
                FisierAtasat fisierAtasatForDelete = serviceFisierAtasat.getById(FisierAtasat.class, fisierAtasatFirma.getFisierAtasat().getId());
                FisierAtasatFirma fisierAtasatFirmaForDelete = serviceFisierAtasatFirma.getById(FisierAtasatFirma.class, fisierAtasatFirma.getId());
                
                serviceFisierAtasatFirma.delete(fisierAtasatFirmaForDelete);
                serviceFisierAtasat.delete(fisierAtasatForDelete);
                setResponsePage(new FirmaEditPage(entity.getId()));
                }
            };
            li.add(delLink);

        }

    }
    
    private Folder getUploadFolder() {
    	
        Folder uploadFolder = MarketApp.get().getUploadFolder();
        Folder firmaUploadFolder = new Folder(uploadFolder, "firme" + (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0 ? "\\" : "/") + entity.getId());
        firmaUploadFolder.mkdirs();
        
        return firmaUploadFolder;
        
    }
    
    private String getStorePath(String fileName) {
        return "firme/" + entity.getId() + "/" + fileName;
    }

    @SuppressWarnings("serial")
	private class FileUploadForm extends Form {
    	
        private TextField<String> tfNumeFisier;
        private TextField<String> tfDescriere;
        private FileUploadField fileUploadField;
	
    	   	
        public FileUploadForm(String name) {
            super(name);

            setMultiPart(true);
            setMaxSize(Bytes.kilobytes(4000));//4MB max
            final AtasamenteListView FilesView = new AtasamenteListView("atasamenteList", entity.getFisierAtasatFirma());
        	final WebMarkupContainer wkRaport = new WebMarkupContainer("wkRaport");
            wkRaport.setOutputMarkupId(true);
            wkRaport.setOutputMarkupPlaceholderTag(true);
            wkRaport.add(FilesView);
            
            //add(tfNumeFisier = new TextField<String>("numeFisier",Model.of("")));
            add(tfDescriere = new TextField<String>("descriere",Model.of("")));
            add(fileUploadField = new FileUploadField("fileInput"));
            add(new FeedbackPanel("feedback"));
            add(wkRaport);
            // add(new AjaxSubmitLink("submitFile") {

                // @Override
                // public void onSubmit(AjaxRequestTarget target, Form FileUploadForm) {
                    // super.onSubmit(target, FileUploadForm);
                    
                    // final List<FileUpload> uploads = fileUploadField.getFileUploads();
                    // if (uploads != null) {
                        // Folder uploadFolder = getUploadFolder();
                        // for (FileUpload upload : uploads) {
                            // File newFile = new File(uploadFolder, upload.getClientFileName());
                            // if (newFile.exists()) {
            					// newFile.delete();
            				// }

                            // try {
                                // newFile.createNewFile();
                                // upload.writeTo(newFile);
                                
                                // FisierAtasat fisierAtasat = new FisierAtasat();
                                // fisierAtasat.setNumeFisier(tfNumeFisier.getInputName());
                                // fisierAtasat.setNumeFisier(upload.getClientFileName());
                                // fisierAtasat.setDescriere(tfDescriere.getInput());
                                // fisierAtasat.setStore(getStorePath(upload.getClientFileName()));
                                
                                // FisierAtasatFirma fisierAtasatFirma = new FisierAtasatFirma();
                                // fisierAtasatFirma.setFisierAtasat(fisierAtasat);
                                // fisierAtasatFirma.setFirma(entity);
                                
                                // serviceFisierAtasat.insert(fisierAtasat);
                                // serviceFisierAtasatFirma.insert(fisierAtasatFirma);
                                
                                // info("fisier salvat: " + upload.getClientFileName());
                                // setResponsePage(new FirmaEditPage(entity.getId()));
                                
                                // FilesView.setList(entity.getFisierAtasatFirma());
                                // FilesView.modelChanged();
                                
                                // target.add(wkRaport);
                                
                            // } catch (Exception e) {
                                // throw new IllegalStateException("Unable to write file", e);
                            // }
                        // }
                    // }
                    
                // }
                
            // });
        
        }
        
        
        
        
       @Override
       protected void onSubmit() {
           final List<FileUpload> uploads = fileUploadField.getFileUploads();
           if (uploads != null) {
               Folder uploadFolder = getUploadFolder();
               for (FileUpload upload : uploads) {
                   File newFile = new File(uploadFolder, upload.getClientFileName());
                   if (newFile.exists()) {
   					newFile.delete();
   				}

                   try {
                       newFile.createNewFile();
                       upload.writeTo(newFile);
                       
                       FisierAtasat fisierAtasat = new FisierAtasat();
                       // fisierAtasat.setNumeFisier(tfNumeFisier.getInputName());
                       fisierAtasat.setNumeFisier(upload.getClientFileName());
                       fisierAtasat.setDescriere(tfDescriere.getInput());
                       fisierAtasat.setStore(getStorePath(upload.getClientFileName()));
                       
                       FisierAtasatFirma fisierAtasatFirma = new FisierAtasatFirma();
                       fisierAtasatFirma.setFisierAtasat(fisierAtasat);
                       fisierAtasatFirma.setFirma(entity);
                       
                       serviceFisierAtasat.insert(fisierAtasat);
                       serviceFisierAtasatFirma.insert(fisierAtasatFirma);
                       
                       info("fisier salvat: " + upload.getClientFileName());
                       setResponsePage(new FirmaEditPage(entity.getId()));
                       // FilesView.setList(entity.getFisierAtasatFirma());
                       // FilesView.modelChanged();
                       
                       // target.add(wkRaport);
                       
                       
                   } catch (Exception e) {
                       throw new IllegalStateException("Unable to write file", e);
                   }
               }
           }
       }
    }
}